import { createRouter, createWebHistory } from "vue-router";
import userLogin from "../components/user/UserLogin.vue"
import { useAuthStore } from "@/stores/LoginUserStore.js";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("../components/BasicLayout.vue"),
    },
    {
      path: "/user/login",
      name: "用户登陆",
      component: userLogin,
    },
    {
      path: "/user/register",
      name: "用户注册",
      component: () => import("../components/user/UserRegister.vue"),
    },
  ],
});
// 添加全局路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();

  // 如果目标路由需要认证
  if (to.meta.requiresAuth) {
    try {
      // 检查本地存储是否有用户数据
      if (localStorage.getItem('user')) {
        authStore.loginSuccess(JSON.parse(localStorage.getItem('user')));
        next();
      } else {
        next('/user/login');
      }
    } catch (error) {
      console.error("认证检查失败:", error);
      next('/user/login');
    }
  } else {
    next();
  }
});

export default router;
